import {isUndefined, toLowerCaseObjKey} from '../core/util'

$.ajaxSetup({
    cache: false,
    success(res) {
        toLowerCaseObjKey(res);
        if (res && res.code === 'kicked') {
            location.href = window.ssoHost + 'message?appid=' + window.ssoAppId +
                '&orgcode=' + res.orgcode + '&w=' + res.message + '&returnurl=' + window.location.href;
        }
    }
});

export default {
    /**
     * 初始化编辑器时获取内容
     */
    initEditorContent() {
        let url = "/api/Editor/GetBookV2";
        let bookId = window.resourceID;
        if(!window.typeId){
            // 课题项目
            url = "/api/Editor/GetBook";
            bookId = window.moduleCode;
        }
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params: {
                    bookId: bookId
                }
            }).then(res => {
                if (res && res.data && res.data.Code === 200) {
                    let originalData = "";
                    let title = "";
                    if (typeof res.data.Data === "object" && res.data.Data) {
                        originalData = res.data.Data.Content || "";
                        title = res.data.Data.Title;
                    } else {
                        originalData = res.data.Data || "";
                        title = "正文";
                    }
                    // 过滤掉参考文献
                    let noQuote = originalData.replace(/<div id="quoteList".+/g, "");
                    // 上传的文档处理图片
                    let changeImgAttr = noQuote.replace(/<img[^>]+/g, function (img) {
                        let changeRole = img.replace(/role="\d+"/g, "role=\"999\"");
                        return changeRole.replace(/style=""/g, "style=\"max-width:100%\"");
                    });
                    resolve({
                        content: changeImgAttr,
                        title: title,
                        resourceCode: res.data.Data.ResourceCode || ''
                    });
                } else {
                    // 接口发送成功但是返回状态不是200
                    // 一般都是cookie导致的请求权限问题
                    console.log(res);
                    reject("openLogin");
                }
            }).catch(err => {
                // 请求接口出错，可能是api的问题
                console.log(err);
                reject("apiError");
            });
        })
    },
    /**
     * 保存内容的接口
     * @return Promise
     */
    saveContent() {
        return new Promise((resolve, reject) => {
            let url = "/api/Editor/BookSyncV2"
              , bookId = window.resourceID;
            if(!window.typeId){
                url = "/api/Editor/BookSync";
                bookId = window.moduleCode;
            }
            UE.getEditor(window.editorId).getKfContent((content) => {
                axios.post(url,
                    qs.stringify({
                        BookId: bookId,
                        Content: content
                    })
                ).then(res => {
                    if (res && res.data && res.data.Code === 200) {
                        resolve(res.data);
                    } else {
                        reject();
                    }
                }).catch(err => {
                    reject(err)
                });
            });
        });
    },
    export(type) {
        let bookId = window.resourceID;
        if(!window.typeId){
            bookId = window.moduleCode;
        }
        return new Promise((resolve, reject) => {
            axios.post(`/api/Editor/BookExportV2?bookId=${bookId}&type=${type}`
            ).then(res => {
                // console.log(res);
                if (res && res.status === 200 && res.data.Code === 200) {
                    resolve(res.data.Data);
                } else {
                    reject(res);
                }
            }).catch(err => {
                reject(err)
            });
        });
    },
    queryStatus(taskId, title) {
        return new Promise((resolve, reject) => {
            axios.get(`/api/Editor/GetConvertStatus?taskId=${taskId}&title=${title}`
            ).then((result) => {
                // console.log(result);
                if (result && result.status === 200 && result.data.Code === 200) {
                    resolve(result.data.Data);
                } else {
                    reject(result);
                }
            }).catch((err) => {
                reject(err);
            });
        });
    }
}
